<?php

/**
 * @copyright   FOSP
 * @version     20120407
 * @todo        Controller Match
 * @name        MatchController
 * @author      QuangTM 
 */
class MatchController extends Zend_Controller_Action
{

    /**
     * 
     * @var int
     */
    private $_matchID = 0;

    /**
     *
     * @var array
     */
    private $_matchDetail = NULL;

    public function preDispatch()
    {
        $this->_matchID = intval($this->_request->getParam('mid', 0));
        $actionName = $this->_request->getActionName();
        // Models instance
        $matchModel = Match::getInstance();

        // Get match detail
        $this->_matchDetail = $matchModel->getMatchDetailByIDs(array($this->_matchID));
        $this->_matchDetail = $this->_matchDetail[0];

        $title = Fpt_Filter::setSeoLink($this->_matchDetail['TeamName1'] . ' vs ' . $this->_matchDetail['TeamName2']);
        if ($title != $this->_request->getParam('title', NULL))
            $this->_redirect(BASE_URL . "/$actionName/tran-$title-{$this->_matchID}");

        // Assign to view
        $this->view->assign(array(
            'matchDetail' => $this->_matchDetail,
            'actionName'  => $this->_request->getActionName(),
            'seoTitle'    => Fpt_Filter::setSeoLink($this->_matchDetail['TeamName1'] . ' vs ' . $this->_matchDetail['TeamName2']),
        ));
    }

    public function thongKeAction()
    {
        // Get models
        $matchStatisticModel  = MatchStatistic::getInstance();
        $reportTypeModel      = ReportType::getInstance();
        $playerTeamMatchModel = PlayerTeamMatch::getInstance();

        // Get report type
        $arrReportTypes = $reportTypeModel->getAllReportType();

        // Get match statistic detail
        // Team 1
        $statisticTeam1 = $matchStatisticModel->getMatchStatistic($this->_matchDetail['Team1'], $this->_matchID);

        // Team 2
        $statisticTeam2 = $matchStatisticModel->getMatchStatistic($this->_matchDetail['Team2'], $this->_matchID);

        $statistic = array();
        if (count($statisticTeam1) && count($statisticTeam2))
        {
            foreach ($arrReportTypes as $reportType)
            {
                $statistic[$reportType['ID']] = array(
                    'Name'       => $reportType['Name'],
                    'Team1Value' => isset($statisticTeam1[$reportType['ID']]) ? $statisticTeam1[$reportType['ID']]['Values'] : 0,
                    'Team2Value' => isset($statisticTeam2[$reportType['ID']]) ? $statisticTeam2[$reportType['ID']]['Values'] : 0,
                );
            }
        }



        // Get players attend match of 2 team
        // Team 1
        $playersTeam1 = $playerTeamMatchModel->getPlayersTeamMatch($this->_matchID, $this->_matchDetail['Team1']);

        // Team 2
        $playersTeam2 = $playerTeamMatchModel->getPlayersTeamMatch($this->_matchID, $this->_matchDetail['Team2']);

        // Assign to view
        $this->view->assign(array(
            'statistic'    => $statistic,
            'playersTeam1' => $playersTeam1,
            'playersTeam2' => $playersTeam2,
        ));

        // Add helper
        $this->view->addHelperPath(APPLICATION_PATH . '/modules/default/views/scripts/match/helper');
    }

    public function danhGiaAction()
    {
        // Get user login
        $session = new Zend_Session_Namespace(SESSION_NAMESPACE);

        // Get userID
        $userID = $session->userid;

        // Get models' instance
        $playerTeamMatchModel  = PlayerTeamMatch::getInstance();
        $ratingPlayerStatistic = RatingPlayerStatistic::getInstance();
        $ratingPlayer          = RatingPlayer::getInstance();
        $playerModel           = Player::getInstance();

        // Get players attend match of 2 team
        // Team 1
        $playersTeam1 = $playerTeamMatchModel->getPlayersTeamMatch($this->_matchID, $this->_matchDetail['Team1']);

        // Team 2
        $playersTeam2 = $playerTeamMatchModel->getPlayersTeamMatch($this->_matchID, $this->_matchDetail['Team2']);

        // Get array player id
        $arrPlayerIDs = array_merge(array_keys($playersTeam1), array_keys($playersTeam2));

        // Get array basic player data
        $arrPlayerData = $playerModel->getBasicDataByIDs($arrPlayerIDs);

        // Get statistic table for this match
        $statisticTable = $ratingPlayerStatistic->getStatisticTable($this->_matchID);

        // Check userid is rated match or not
        $isRated = FALSE;
        if ($userID !== NULL)
            $isRated = $ratingPlayer->checkPlayerIsRatedMatch($userID, $this->_matchID);

        // Check rate is alive
        $endTime  = $this->_matchDetail['DatetimeHappen'] + 122400;
        $currTime = time();
        if ($this->_request->getParam('alive', NULL))
            $alive    = TRUE;
        else
            $alive    = $currTime > $endTime ? FALSE : TRUE;

        // Assign to view
        $this->view->assign(array(
            'playersTeam1'   => $playersTeam1,
            'playersTeam2'   => $playersTeam2,
            'userID'         => (int) $userID,
            'arrPlayerData'  => $arrPlayerData,
            'statisticTable' => $statisticTable,
            'active'         => $alive,
            'isRated'        => $isRated,
            'attendPlayers1' => array(),
            'attendPlayers2' => array(),
        ));

        // Add helper
        $this->view->addHelperPath(APPLICATION_PATH . '/modules/default/views/scripts/match/helper');

        // Add JS
        $this->view->headScript()->appendFile($this->view->config['js'] . '/player_rating.js')
            ->appendFile($this->view->config['js'] . '/lightbox.js');
    }

    public function thamGiaDanhGiaAction()
    {
        // Disable render layout
        $this->_helper->layout->disableLayout(true);
        $this->_helper->viewRenderer->setNoRender(true);

        // Get user login
        $session = new Zend_Session_Namespace(SESSION_NAMESPACE);

        // Get params
        $userId          = intval($this->_request->getParam('userid', 0));
        $arrRatedPlayers1 = $this->_request->getParam('players1', NULL);
        $arrRatedPlayers2 = $this->_request->getParam('players2', NULL);

        // default response
        $response = array(
            'error' => 0,
            'msg'   => 'Success',
            'html'  => NULL
        );

        if ($userId == $session->userid && is_array($arrRatedPlayers1) && count($arrRatedPlayers1) && is_array($arrRatedPlayers2) && count($arrRatedPlayers2))
        {
            try
            {
                // Get models' instance
                $ratingPlayerModel          = RatingPlayer::getInstance();
                $ratingPlayerStatisticModel = RatingPlayerStatistic::getInstance();
                
                $statisticTable = array();
                
                // Add and update statistic
                foreach ($arrRatedPlayers1 as $playerID => $rate)
                {
                    $ratingPlayerModel->addRatedPlayer(array(
                        'MatchID'  => $this->_matchID,
                        'TeamID'   => $this->_matchDetail['Team1'],
                        'PlayerID' => $playerID,
                        'UserID'   => $userId,
                        'Rating'   => $rate,
                    ));
                    array_push($statisticTable, array(
                        'match_id'     => $this->_matchID,
                        'player_id'    => $playerID,
                        'rating_user'  => $rate,
                        'team_id'      => $this->_matchDetail['Team1'],
                        'total_userid' => 1,
                    ));
                }
                
                foreach ($arrRatedPlayers2 as $playerID => $rate)
                {
                    $ratingPlayerModel->addRatedPlayer(array(
                        'MatchID'  => $this->_matchID,
                        'TeamID'   => $this->_matchDetail['Team2'],
                        'PlayerID' => $playerID,
                        'UserID'   => $userId,
                        'Rating'   => $rate,
                    ));
                    array_push($statisticTable, array(
                        'match_id'     => $this->_matchID,
                        'player_id'    => $playerID,
                        'rating_user'  => $rate,
                        'team_id'      => $this->_matchDetail['Team2'],
                        'total_userid' => 1,
                    ));
                }
                
                $ratingPlayerStatisticModel->modifyStatisticTable($statisticTable, $this->_matchID);
            }
            catch (Exception $exc)
            {
                $response['error'] = $exc->getCode();
                $response['msg'] = $exc->getMessage();
            }
        }
        else
        {
            $response['error'] = 1;
            $response['msg']   = 'Invalid parameters';
        }

        echo Zend_Json::encode($response);

        exit();
    }

}